package org.example.demo3.untils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.beanutils.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class BeanCopyUtils {
    private static MapperFacade mapper;
    public static <T> T copyBean(Object source, Class<T> target) {
        // 创建目标对象
        T result = null;
        try {
            result = target.getDeclaredConstructor().newInstance();
            if (source != null) {
                // 实现属性copy
                BeanUtils.copyProperties(source, result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回结果
        return result;
    }

    public static  <O,V> List<V> copyBeanList(List<O> list,Class<V> clazz){


        List<V> result = list.stream()
                .map(o -> copyBean(o, clazz))
                .collect(Collectors.toList());
        return result;
    }

    public static <S,D> Page<D> toPage(Page<S> source, Class<D> destinationClass) {
        if (EmptyUtil.isNullOrEmpty(source)){
            return null;
        }
        Class<? extends Page> handlerClass = source.getClass();
        Page<D> destination = mapper.map(source, handlerClass);
        destination.setRecords(mapper.mapAsList(source.getRecords(),destinationClass));
        return destination;
    }

}
